package com.molichuxing.gateway.bff.basic.services.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.molichuxing.framework.exception.BizException;
import com.molichuxing.framework.result.ResponseCodeEnum;
import com.molichuxing.gateway.bff.basic.convertor.Convert;
import com.molichuxing.gateway.bff.basic.entity.response.CityInitialVo;
import com.molichuxing.gateway.bff.basic.entity.response.RegionCityVo;
import com.molichuxing.gateway.bff.basic.entity.response.VehicleDeliveryVo;
import com.molichuxing.gateway.bff.basic.services.BasicBffService;
import com.molichuxing.gateway.bff.car.entity.response.CarOrderCheckVo;
import com.molichuxing.services.business.dto.response.CarDetailBizDto;
import com.molichuxing.services.business.service.CarBizService;
import com.molichuxing.services.business.service.RegionBizService;
import com.molichuxing.services.business.service.VehicleBizService;
import com.molichuxing.services.infrastructure.dto.response.OrderDto;
import com.molichuxing.services.infrastructure.dto.response.OrderExclusivelDto;
import com.molichuxing.services.infrastructure.dto.response.OrderSubscribeDto;
import com.molichuxing.services.infrastructure.dto.response.RegionCityDto;
import com.molichuxing.services.infrastructure.dto.response.RegionDto;
import com.molichuxing.services.infrastructure.dto.response.VehicleColorDto;
import com.molichuxing.services.infrastructure.service.DeliveryParamDicService;
import com.molichuxing.services.infrastructure.service.IovCarService;
import com.molichuxing.services.infrastructure.service.OrderExclusivelService;
import com.molichuxing.services.infrastructure.service.OrderService;
import com.molichuxing.services.infrastructure.service.OrderSubscribeService;
import com.molichuxing.services.infrastructure.service.RegionService;
import com.molichuxing.services.infrastructure.service.StoreService;
import com.molichuxing.services.infrastructure.service.VehicleColorService;
import com.molichuxing.services.property.OrderTypeEnum;

@Service("basicBffService")
public class BasicBffServiceImpl implements BasicBffService {
    private static final Logger logger = LoggerFactory.getLogger(BasicBffServiceImpl.class);

    @Resource
    private StoreService storeService;
    @Resource
    RegionService regionService;

    @Resource
    private RegionBizService regionBizService;

    @Resource
    DeliveryParamDicService deliveryParamDicService;

    @Resource
    private OrderSubscribeService orderSubscribeService;

    @Resource
    private OrderExclusivelService orderExclusivelService;

    @Resource
    private VehicleBizService vehicleBizService;

    @Resource
    private VehicleColorService vehicleColorService;

    @Resource
    private CarBizService carBizService;

    @Resource
    private OrderService orderService;

    @Resource
    private IovCarService iovCarService;

    /**
     * 获取城市
     *
     * @return
     * @throws Exception
     */
    @Override
    public List<CityInitialVo> getRegionList() throws Exception {
        List<Integer> regionId = storeService.getRegionId();
        Map<String, List<RegionDto>> cityMap = regionService.getCityByInitial(regionId);
        if (null == cityMap) {
            return null;
        }

        return Convert.toRegionList(cityMap);
    }

    @Override
    public List<RegionCityVo> getAllCity(Integer level) {
        List<RegionCityVo> regionCityVoList =  new ArrayList<RegionCityVo>();

        List<RegionCityDto> regionCityDtoList  =  regionBizService.getAllCity(level);
        if(regionCityDtoList.size()<=0){
            return  regionCityVoList;
        }
        regionCityVoList =  Convert.toRegionCityVoList(regionCityDtoList);
        return  regionCityVoList;
    }

    @Override
    public VehicleDeliveryVo getDeliveryParamDicByModelId(Integer modelId,Long orderCode,Integer carId)throws Exception {
        VehicleDeliveryVo vehicleDeliveryVo = new VehicleDeliveryVo();
        if (modelId == null || modelId <= 0) {
            throw new BizException(ResponseCodeEnum.UNKNOWN_ERROR.getCode(), "modealId为空");
        }

        Map<String, Object> param = new HashMap<>();
        param.put("modelId", modelId);
        vehicleDeliveryVo.setDeliveryParamDicList(Convert.toDeliveryParamDicVoList(deliveryParamDicService.getDeliveryParamDicByParam(param)));

        //查询订单类型
        OrderDto orderDto = orderService.getOrder(orderCode);
        if (null == orderDto) {
            throw new Exception("非法入参");
        }

        CarOrderCheckVo carOrderCheckVo = new CarOrderCheckVo();

        Integer userId = null;
        String goodsNameStr = "";
        if (OrderTypeEnum.EXCLUSIVEL.equals(orderDto.getType())) {
            // 专属里程订单
            OrderExclusivelDto orderExclusivelDto = orderExclusivelService.getOrderExclusivel(orderCode);
            if (null == orderExclusivelDto) {
                throw new Exception("非法入参");
            }

            userId = orderExclusivelDto.getUserId();
            carOrderCheckVo.setOrderType(OrderTypeEnum.EXCLUSIVEL.getValue());
            //车型名称+规格（是否回购/租期/付款方式）  例：北汽新能源EC 220 经典版 回购/36期/全款
            goodsNameStr = (orderExclusivelDto.getIsBuyback() ? "回购/" : "不回购/").concat(orderExclusivelDto.getTransportTime() + "期/").concat(orderExclusivelDto.getPaymentMethod().getName().equals("分期")?"月付":orderExclusivelDto.getPaymentMethod().getName());
        } else if (OrderTypeEnum.SUBSCRIBE.equals(orderDto.getType())) {
            // 订阅里程订单
            OrderSubscribeDto orderSubscribeDto = orderSubscribeService.getOrderSubscribe(orderCode);
            if (null == orderSubscribeDto) {
                throw new Exception("非法入参");
            }

            userId = orderSubscribeDto.getUserId();
            carOrderCheckVo.setOrderType(OrderTypeEnum.SUBSCRIBE.getValue());
            //车型名称+规则（租期/基础里程，订阅里程）   例：北汽新能源 EC 220 精英版 1个月/500公里，300公里
            goodsNameStr = (orderSubscribeDto.getTransportTime() + "个月/").concat(orderSubscribeDto.getBaseMileage() + "公里,").concat(orderSubscribeDto.getPackageMileage() + "公里");
        }
        vehicleDeliveryVo.setGoodsName(goodsNameStr);
        //获取车辆信息
        CarDetailBizDto carDetailBizDto = carBizService.getCarDetail(carId);
        if (null == carDetailBizDto) {
            throw new Exception("非法入参");
        }
        //获取车型名称
        String vehicleName = vehicleBizService.getVehicleName(carDetailBizDto.getVehicleId());
        if (null == vehicleName) {
            throw new Exception("非法入参");
        }
        //获取车身颜色
        VehicleColorDto vehicleColorDto = vehicleColorService.getVehicleColorByvehicleColorId(carDetailBizDto.getVehicleColorId());
        if (null == vehicleColorDto) {
            throw new Exception("非法入参");
        }
        vehicleDeliveryVo.setGoodsName(vehicleName + " " + goodsNameStr);
        vehicleDeliveryVo.setVehicleColor(vehicleName + "/" + vehicleColorDto.getName());
        vehicleDeliveryVo.setEngineCode(carDetailBizDto.getEngineCode());
		// 车辆里程-仪表盘
        vehicleDeliveryVo.setMileage(iovCarService.getCurrentMileage(carDetailBizDto.getVin()));
        
        return vehicleDeliveryVo;
    }
}
